package com.mmall.demo2;

import com.mmall.demo2.model.Permission;
import com.mmall.demo2.model.Role;
import com.mmall.demo2.model.User;
import com.mmall.demo2.service.UserService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;


import java.util.*;

/**
 * @Auther guo
 * @Date 2018/12/15 10:40
 * @Description $end$
 */
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    //认证授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取登录时塞入的三个对象，并取出第一个
        User user = (User)principalCollection.fromRealm(this.getClass().getName()).iterator().next();
        List<String> permissionList = new ArrayList<>();
        Set<String> rolesList = new HashSet<>();
        Set<Role> roles = user.getRoles();
        if (CollectionUtils.isNotEmpty(roles)){
            for (Role role : roles) {
                rolesList.add(role.getRname());
                Set<Permission> permissions = role.getPermissions();
                if (CollectionUtils.isNotEmpty(permissions)){
                    for (Permission permission : permissions) {
                        permissionList.add(permission.getName());
                    }
                }
            }
        }
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(rolesList);
        info.addStringPermissions(permissionList);
        return info;
    }

    //认证登录
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken toke) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)toke;
        String username = usernamePasswordToken.getUsername();
        User user = userService.findByUsername(username);

        //如果查询不到就返回null
        if (user == null) {
            return null;
        }
        //过滤器会自动判断 toke中的password 值是否和传输的 password值一致
        return new SimpleAuthenticationInfo(user,user.getPassword(),this.getClass().getName());
    }
}
